﻿(function () {
    function xml_loadFile(xmlUrl, funcAsync) {
        var xmlDoc = null;
        var isChrome = false;
        var asyncIs = (null != funcAsync);    // 是否是异步加载。当funcAsync不为空时，使用异步加载，否则是同步加载。  

        // 检查参数  
        if ("" == xmlUrl) return null;
        if (asyncIs) {
            if ("function" != typeof (funcAsync)) return null;
        }

        // 创建XML对象  
        try {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");    // Support IE  
        }
        catch (ex) {
        }
        if (null == xmlDoc) {
            try {
                // Support Firefox, Mozilla, Opera, etc  
                xmlDoc = document.implementation.createDocument("", "", null);    // 创建一个空的 XML 文档对象。  
            }
            catch (ex) {
            }
        }
        if (null == xmlDoc) return null;

        // 加载XML文档  
        xmlDoc.async = asyncIs;
        if (asyncIs) {
            if (window.ActiveXObject) {
                xmlDoc.onreadystatechange = function () {
                    if (xmlDoc.readyState == 4) {
                        var isError = false;
                        if (null != xmlDoc.parseError) {
                            isError = (0 != xmlDoc.parseError.errorCode);    // 0成功, 非0失败。  
                        }
                        funcAsync(xmlDoc, isError);
                    }
                }
            }
            else {
                xmlDoc.onload = function () {
                    funcAsync(xmlDoc, false);
                }
            }
        }
        try {
            xmlDoc.load(xmlUrl);
        }
        catch (ex) {
            // alert(ex.message)    // 如果浏览器是Chrome，则会catch这个异常：Object # (a Document) has no method "load"  
            isChrome = true;
            xmlDoc = null;
        }
        if (isChrome) {
            var xhr = new XMLHttpRequest();
            if (asyncIs)    // 异步  
            {
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        funcAsync(xhr.responseXML, xhr.status != 200);
                    }
                }
                xhr.open("GET", xmlUrl, true);
                try    // 异步模式下，由回调函数处理错误。  
                {
                    xhr.send(null);
                }
                catch (ex) {
                    funcAsync(null, true);
                    return null;
                }
                return xhr;    // 注意：返回的是XMLHttpRequest。建议异步模式下仅用null测试返回值。  
            }
            else    // 同步  
            {
                xhr.open("GET", xmlUrl, false);
                xhr.send(null);    // 同步模式下，由调用者处理异常  
                xmlDoc = xhr.responseXML;
            }
        }
        return xmlDoc;
    }
    function getAttributeValue(xmlNode, attrName) {
        if (!xmlNode) return "";
        if (!xmlNode.attributes) return "";
        if (xmlNode.attributes[attrName] != null) return xmlNode.attributes[attrName].value;
        if (xmlNode.attributes.getNamedItem(attrName) != null) return xmlNode.attributes.getNamedItem(attrName).value;
        return "";
    }
    if (!window.ActiveXObject) {
        XMLDocument.prototype.selectSingleNode = Element.prototype.selectSingleNode = function (xpath) {
            var nsResolver = this.createNSResolver(this.ownerDocument == null ? this.documentElement : this.ownerDocument.documentElement),
                result = this.evaluate(xpath, this, nsResolver, 0, null);
            return result.iterateNext();
        }
        XMLDocument.prototype.selectNodes = Element.prototype.selectNodes = function (xpath) {
            var nsResolver = this.createNSResolver(this.ownerDocument == null ? this.documentElement : this.ownerDocument.documentElement),
                result = this.evaluate(xpath, this, nsResolver, 0, null),
                found = [],
                res;
            while (res = result.iterateNext()) found.push(res);
            return found;
        }
    }
    var regionXML = xml_loadFile("/region.xml");
    try {
        regionXML.setProperty("SelectionLanguage", "XPath");
    }
    catch (ex) { }
    $(document).ready(function () {
        $("select[selectset=regions]").bind("change", function () { ChooiceRegion($(this).attr("id"), $(this).val()); });
    });

    function ChooiceRegion(currentControlId, selectedRegionId) {
        var depth = GetDepthBySelectId(currentControlId);
        var hasvalue = (selectedRegionId != null && selectedRegionId.length > 0);

        // 更新当前选择的地区
        if (hasvalue)
            $("#regionSelectorValue").val(selectedRegionId);
        else {
            if (depth == 1)
                $("#regionSelectorValue").val("");
            else
                $("#regionSelectorValue").val($("#ddlRegions" + (depth - 1)).val());
        }

        // 重置所有子区域的显示
        var subDepth = depth + 1;
        var subSelector = $("#ddlRegions" + subDepth);

        while (subSelector.length > 0) {
            ResetSelector(subSelector);
            subDepth++;
            subSelector = $("#ddlRegions" + subDepth);
        }

        var haschild = (subDepth > (depth + 1));

        // 更新直接子区域的内容
        if (hasvalue && haschild) {
            FillSelector(selectedRegionId, $("#ddlRegions" + (depth + 1)), "");
        }
    }

    function GetDepthBySelectId(currentControlId) {
        return eval(currentControlId.replace("ddlRegions", ""));
    }

    // 手工设置当前要选中的地区
    window.ResetSelectedRegion = function (regionId) {
        $.ajax({
            url: "RegionHandler.aspx",
            type: 'post', dataType: 'json', timeout: 10000,
            data: { action: "getregioninfo", regionId: regionId },
            success: function (resultData) {
                if (resultData.Status != "OK")
                    return;

                var depth = parseInt(resultData.Depth);
                if (depth == 1) {
                    $("#ddlRegions1").val(resultData.RegionId);
                    $("#ddlRegions2").val(null);
                    $("#ddlRegions3").val(null);
                }

                else {
                    var pathArr = resultData.Path.split(",");
                    $("#ddlRegions1").val(pathArr[0]);

                    for (index = 1; index < pathArr.length && index < depth; index++) {
                        var selector = $("#ddlRegions" + (index + 1));
                        ResetSelector(selector);
                        FillSelector(pathArr[index - 1], selector, pathArr[index]);
                        if (depth == 2) {
                            $("#ddlRegions3").val(null);
                        }
                    }
                }

                $("#regionSelectorValue").val(resultData.RegionId);
            }
        });
    }

    // 重置指定的下拉选择框
    function ResetSelector(selector) {
        $(selector).find("option").remove();
        $(selector).append("<option value=\"\">" + $("#regionSelectorNull").val() + "</option>");
    }

    // 根据指定的父地区编号填充地区下拉框的可选内容
    function FillSelector(parentId, selector, selectedValue) {
        var dom,
            func = function () {
                if (selector.attr("id") == "ddlRegions2") {
                    var ddlRegions = $("select[selectset=regions]");
                    $(".sonic").show();
                    sonic.play();
                    $(".Zipcode_msg").text("正在获取中...");
                    $.post("RegionHandler.aspx", "action=getzcode&county=" + ddlRegions[0].options[ddlRegions[0].selectedIndex].text, function (e) {
                        $("#SubmmitOrder_txtZipcode").val(e);
                        sonic.stop();
                        $(".sonic").hide();
                        $(".Zipcode_msg").text("");
                    });
                }
                else if (selector.attr("id") == "ddlRegions3") {
                    var ddlRegions = $("select[selectset=regions]");
                    $(".sonic").show();
                    sonic.play();
                    $(".Zipcode_msg").text("正在获取中...");
                    $.post("RegionHandler.aspx", "action=getzcode&province=" + ddlRegions[0].options[ddlRegions[0].selectedIndex].text + "&county=" + ddlRegions[1].options[ddlRegions[1].selectedIndex].text, function (e) {
                        $("#SubmmitOrder_txtZipcode").val(e);
                        sonic.stop();
                        $(".sonic").hide();
                        $(".Zipcode_msg").text("");
                    });
                }
            };
        dom = regionXML.selectSingleNode("//*[@id='" + parentId + "']");
        if (dom != null) {
            var list;
            if (typeof (dom.children) != "undefined") list = dom.children;
            else list = dom.childNodes;
            if (list.length == 0) {
                func();
                return;
            }
            for (var i = 0; i < list.length; i++) {
                var name = getAttributeValue(list[i], "name");
                if (name != null && name != "") {
                    var option = document.createElement("option");
                    option.text = name;
                    option.value = getAttributeValue(list[i], "id");
                    $(selector)[0].options.add(option);
                }
            }
            if (selectedValue.length > 0) {
                $(selector).val(selectedValue);
            }
        }
        else {
            func();
        }
        //$.ajax({
        //    url: "RegionHandler.aspx",
        //    type: 'post', dataType: 'json', timeout: 10000,
        //    data: { action: "getregions", parentId: parentId },
        //    success: function (resultData) {
        //        var func = function () {
        //            if (selector.attr("id") == "ddlRegions2") {
        //                var ddlRegions = $("select[selectset=regions]");
        //                $(".sonic").show();
        //                sonic.play();
        //                $(".Zipcode_msg").text("正在获取中...");
        //                $.post("RegionHandler.aspx", "action=getzcode&county=" + ddlRegions[0].options[ddlRegions[0].selectedIndex].text, function (e) {
        //                    $("#SubmmitOrder_txtZipcode").val(e);
        //                    sonic.stop();
        //                    $(".sonic").hide();
        //                    $(".Zipcode_msg").text("");
        //                });
        //            }
        //            else if (selector.attr("id") == "ddlRegions3") {
        //                var ddlRegions = $("select[selectset=regions]");
        //                $(".sonic").show();
        //                sonic.play();
        //                $(".Zipcode_msg").text("正在获取中...");
        //                $.post("RegionHandler.aspx", "action=getzcode&province=" + ddlRegions[0].options[ddlRegions[0].selectedIndex].text + "&county=" + ddlRegions[1].options[ddlRegions[1].selectedIndex].text, function (e) {
        //                    $("#SubmmitOrder_txtZipcode").val(e);
        //                    sonic.stop();
        //                    $(".sonic").hide();
        //                    $(".Zipcode_msg").text("");
        //                });
        //            }
        //        };
        //        if (resultData == null) {
        //            func();
        //            return;
        //        }
        //        if (resultData.Status == "OK") {
        //            if (resultData.Regions.length == 0) {
        //                func();
        //                return;
        //            }
        //            $.each(resultData.Regions, function (i, region) {
        //                var option = document.createElement("option");
        //                option.text = region.RegionName;
        //                option.value = region.RegionId;
        //                $(selector)[0].options.add(option);
        //            });

        //            if (selectedValue.length > 0) {
        //                $(selector).val(selectedValue);
        //            }
        //        }
        //        else {
        //            func();
        //        }
        //    }
        //});
    }

    // 获取当前选择的地区编号
    function GetSelectedRegionId() {
        return $("#regionSelectorValue").val();
    }
})();